package com.dcy.daily.skill.rabbitMQ.springAMQP.util;

import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitAdmin;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

/**
 * 不使用Springboot自启动配置spring-amqp时使用。其中CachingConnectionFactory为单例。
 * 懒汉式
 * @author duanchunyu
 * @version 1.0.0
 * @createTime 2021年08月02日 14:53
 */
public class AmqpUtil {

    private static CachingConnectionFactory connectionFactory;


    private AmqpUtil(){}

    /**
     * 获得RabbitTemplate
     * @return
     */
    public static RabbitTemplate getRabbitTemplate(){
        connectionFactory = getConnectionFactoryInstance();
        RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
        return rabbitTemplate;
    }

    /**
     * 获得RabbitAdmin
     * @return
     */
    public static RabbitAdmin getRabbitAdmin(){
        connectionFactory = getConnectionFactoryInstance();
        RabbitAdmin admin = new RabbitAdmin(connectionFactory);
        return admin;
    }

    public static CachingConnectionFactory getConnectionFactoryInstance(){
        if(connectionFactory == null){
            connectionFactory = new CachingConnectionFactory();
        }
        connectionFactory.setHost("centos-node-135");
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        connectionFactory.setPort(5672);
        connectionFactory.setPublisherConfirmType(CachingConnectionFactory.ConfirmType.CORRELATED);
        return connectionFactory;
    }
}
